/*
 * @lc app=leetcode.cn id=206 lang=typescript
 *
 * [206] 反转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

//  思想：
//  迭代法：利用pre和next保存当前节点，然后遍历数组逐一进行置换
//  递归法：只要考虑head和后面已经反转的节点即可，注意设置base
//  复杂度：O(n) O(1)

function reverseList(head: ListNode | null): ListNode | null {
    // 迭代
    // let prev = null;
    // let curr = head;
    // while (curr) {
    //     const next = curr.next;
    //     curr.next = prev;
    //     prev = curr;
    //     curr = next;
    // }
    // return prev;

    // 递归：
    if (!head) return head
    if (!head.next) return head
    let last = reverseList(head.next)
    head.next.next = head
    head.next = null
    return last

};
// @lc code=end

import { ListNode } from './type'

const head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))))

console.log(ListNode.printList(head));
console.log(ListNode.printList(reverseList(head)));
